import Sortable from '@timluo465/react-sortablejs';
import { WeaNewScroll } from 'ecCom';
import { observer } from 'mobx-react';
import React from "react";
import { DragKey } from "../../../../constants/form";
import { onMove } from '../sortable';
import Toggle from "../toggle";
import FormField from "./field";

@observer
export default class LeftMenu extends React.Component {
  static defaultProps = {
    datas: [],
    renderItem: null,
    onDragEnd: () => { }
  }

  leftRef = React.createRef();
  
  componentDidMount() {
    const dom = this.leftRef.current;

    // work around 
    // SortableJS 拖拽元素->clone->drop clone元素会替代原有的元素且绑定的click事件会被移除
    // 导致拖拽插件后 再次点击插件无法添加该类型插件
    dom.addEventListener('click', e => {
      const { target } = e;
      let dom = null;

      if (this.isComEl(target)) {
        dom = target;
      } else if (this.isComEl(target.parentNode)) {
        dom = target.parentNode;
      }

      if (!dom) return;

      const type = dom.getAttribute('data-id');

      this.props.onDragEnd({ type });
    });
  }

  isComEl(el) {
    return el.classList.contains('wea-edc-com');
  }

  renderItem = item => {
    const { renderItem } = this.props;

    if (renderItem) {
      return (
        <div className='wea-edc-com' data-id={item.type}>
          {renderItem(item)}
        </div>
      );
    }

    return <FormField ecId={`${this && this.props && this.props.ecId || ''}_FormField@a1lf2z`} field={item} />;
  }
  
  onDragEnd = e => {
    const { newIndex, item, from, to } = e;
    
    // 未拖至设计器内
    if (from === to) return;

    const uuid = to.getAttribute("data-uuid");
    const type = item.getAttribute("data-id");
    const name = item.textContent;
    const newCom = { type, name };
    let index = newIndex;

    if (uuid) {
      newCom.pid = uuid;
      index = to.getAttribute("data-index");
      // index中包含下划线_则为表格布局
      index = ~index.indexOf('_') ? 
        index.split('_').map(n => parseInt(n)) : parseInt(index);
    }

    this.props.onDragEnd(newCom, index);
  }

  render() {
    const { datas } = this.props;

    return (
      <div className='ef-left' ref={this.leftRef}>
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@9fj7vz`} height='100%'>
          {datas.map(({ category, coms }) => (
            <Toggle ecId={`${this && this.props && this.props.ecId || ''}_Toggle@zpas5o@${category}`} title={category} key={category}>
              <Sortable ecId={`${this && this.props && this.props.ecId || ''}_Sortable@3az316@${category}`}
                options={{
                  sort: false,
                  group: {
                    name: DragKey.ComCard,
                    pull: 'clone',
                    put: false
                  },
                  onMove,
                  onEnd: this.onDragEnd,
                  // setData 兼容火狐浏览器拖拽组件后 自动打开新页面问题
                  setData: function setData(dataTransfer) {
                    dataTransfer.setData('Text', '');
                  }
                }}
              >
                {coms.map(this.renderItem)}
              </Sortable>
            </Toggle>
          ))}
        </WeaNewScroll>
      </div>
    );
  }
}